<template>
  <div 
    :class="[
      'bx-collapse',
      'bx-glass'
    ]"
  >
    <slot></slot>
  </div>
</template>

<script>
import { provide, ref, watch } from 'vue'

export default {
  name: 'BxCollapse',
  props: {
    modelValue: {
      type: [String, Array],
      default: () => []
    },
    accordion: {
      type: Boolean,
      default: false
    }
  },
  emits: ['update:modelValue', 'change'],
  setup(props, { emit }) {
    const activeNames = ref([])

    watch(() => props.modelValue, (newVal) => {
      if (props.accordion && Array.isArray(newVal) && newVal.length > 1) {
        activeNames.value = [newVal[0]]
      } else if (Array.isArray(newVal)) {
        activeNames.value = newVal
      } else if (typeof newVal === 'string') {
        activeNames.value = [newVal]
      } else {
        activeNames.value = []
      }
    }, { immediate: true })

    const handleItemClick = (name) => {
      if (props.accordion) {
        activeNames.value = activeNames.value[0] === name ? [] : [name]
      } else {
        const index = activeNames.value.indexOf(name)
        if (index > -1) {
          activeNames.value.splice(index, 1)
        } else {
          activeNames.value.push(name)
        }
      }
      emit('update:modelValue', props.accordion ? activeNames.value[0] : activeNames.value)
      emit('change', props.accordion ? activeNames.value[0] : activeNames.value)
    }

    provide('collapseContext', {
      activeNames,
      handleItemClick
    })

    return {
      activeNames
    }
  }
}
</script>

<style scoped>
.bx-collapse {
  border: 1px solid var(--bx-glass-border);
  border-radius: var(--bx-radius-medium);
  overflow: hidden;
  font-family: var(--bx-font-family);
}
</style>

